<template>
	<view class="container calc_form">
		<uni-forms :modelValue="formData" ref="regRef" validateTrigger="blur">
      <uni-section title="">
          <uni-forms-item label="学年" required >
            <uni-easyinput type="string" v-model="formData.schoolYear" :disabled="true"/>
          </uni-forms-item>

          <uni-forms-item label="学期" required>
            <uni-easyinput type="string" v-model="formData.semester" :disabled="true"/>
          </uni-forms-item>

          <uni-forms-item label="班级名称" required>
            <uni-easyinput type="string" v-model="formData.className" :disabled="true"/>
          </uni-forms-item>

          <uni-forms-item label="应到人数" required name="studentTotalNum">
            <uni-easyinput type="number" v-model="formData.studentTotalNum" placeholder="请输入学生应到人数"/>
          </uni-forms-item>

          <uni-forms-item label="实到人数" required name="studentAttendNum">
            <uni-easyinput type="number" v-model="formData.studentAttendNum" placeholder="请输入学生实到人数"/>
          </uni-forms-item>

          <uni-forms-item label="任课教师" required>
            <uni-easyinput type="string" v-model="formData.teacherName" :disabled="true"/>
          </uni-forms-item>

          <uni-forms-item label="教师工号" required>
            <uni-easyinput type="string" v-model="formData.teacherCode" :disabled="true"/>
          </uni-forms-item>

          <uni-forms-item label="教师所属部门" required>
            <uni-easyinput type="string" v-model="formData.teacherDepartment" :disabled="true"/>
          </uni-forms-item>

          <uni-forms-item label="教师类别" required name="teacherEmploymentType">
            <uni-data-checkbox v-model="formData.teacherEmploymentType" :localdata="teacherEmploymentType"/>
          </uni-forms-item>

          <uni-forms-item label="课程名称" required>
            <uni-easyinput type="string" v-model="formData.courseName" :disabled="true"/>
          </uni-forms-item>

          <uni-forms-item label="上课地点" required>
            <uni-easyinput type="string" v-model="formData.location"/>
          </uni-forms-item>

          <uni-forms-item label="听课日期" required name="teachDate">
            <picker mode="date" :value="formData.teachDate" :start="startDate" :end="endDate" @change="bindDateChange">
              <uni-easyinput type="string" v-model="formData.teachDate" @change="bindDateChange" :clearable=false />
            </picker>
          </uni-forms-item>

          <uni-forms-item label="听课小节" required name="teachSection">
            <uni-easyinput type="number" v-model="formData.teachSection" placeholder="请输入听课小节数"/>
          </uni-forms-item>

          <uni-forms-item label="小节内容" required>
            <uni-easyinput type="string" v-model="formData.courseContent" :disabled="true"/>
          </uni-forms-item>
          <uni-forms-item label="课堂现场照片" required>
          <view class="container">
             <!-- 若有图片路径，显示图片 -->
             <image v-if="teachImg" :src="teachImg" mode="aspectFit"></image>
             <!-- 拍照按钮 -->
             <button @click="takePhoto">拍照</button>
           </view>
          </uni-forms-item>
      </uni-section>
    </uni-forms>
    <view class="example btn_submit">
      <button type="primary" @click="goProStage()">下一步</button>
    </view>
  </view>
</template>

<script>
import {getToken, isLogin} from '../../../utils/auth';
import {addRecord} from '../../api/eval';
import {teacherEmploymentType} from '../../../utils/enums';
import {getCourseDetail} from "@/api/course";

export default {
	onLaunch: function() {
	},
	onLoad: function(option) {
		isLogin(this);
    // 从传参中获取teachRecordId
    this.formData.teachRecordId = this.$route.query.teachRecordId;
    console.log(this.formData.teachRecordId)
    if(this.formData.teachRecordId === null || this.formData.teachRecordId === undefined){
      uni.showToast({
        title: '请先选择课程',
        icon: 'error',
        duration: 2000,
        complete: function () {
          // 跳转选择课程页面
          uni.redirectTo({
            url: `/pages/eval/index`,
          })
        }
      });
    }
    // 获取课程详情并赋值
    this.getTeachRecordInfo(this.formData.teachRecordId);
    // 学期学年赋值
    this.getAcademicYearAndSemester();
	},
  onReady() {
    this.$refs.regRef.setRules(this.formRules);
    this.formData.teachDate = this.getDate();
  },
  computed: {
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      console.log(this.getDate('start'))
      return this.getDate('end');
    },
  },
	data() {
		return {
      index: 0,
			teacherEmploymentType,
			params: {
			},
      teachImg: "",
			formData: {
				teachRecordId: "",
				schoolYear: "",
				semester: "",
				className: "",
				studentTotalNum: null,
				studentAttendNum: null,
				teacherName: "",
				teacherCode: "",
				teacherDepartment: "",
				teacherEmploymentType: 1,
				courseId: "",
				courseName: "",
				courseContent: "",
				location: "",
				teachDate: "",
				teachSection: null,
        teachImg:""
			},
      formRules: {
        studentTotalNum: {
          rules: [{
            required: true,
            errorMessage: " ",
          }]
        },
        studentAttendNum: {
          rules: [{
            required: true,
            errorMessage: " ",
          }]
        },
        teacherEmploymentType: {
          rules: [{
            required: true,
            errorMessage: " ",
          }]
        },
        teachDate: {
          rules: [{
            required: true,
            errorMessage: " ",
          }]
        },
        teachSection: {
          rules: [{
            required: true,
            errorMessage: " ",
          }]
        },
      }
		}
	},
	methods: {
    // 上课日期选择
    bindDateChange: function(e) {
      this.formData.teachDate = e.detail.value
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 1;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    // 根据授课记录获取授课详情
    getTeachRecordInfo(teachRecordId){
      const _that = this;
      getCourseDetail(teachRecordId).then(response => {
        console.log(response);
        let data = response.data;
        if(data.id == null || data.id == undefined){
          uni.showToast({
            title: '未找到相关上课记录',
            icon: 'error',
            duration: 1000,
            complete: function () {
              // 跳转选择课程页面
              uni.redirectTo({
                url: `/pages/eval/index`,
              })
            }
          });
        }
        // 课程详情赋值
        _that.formData.className = data.ctitle;
        _that.formData.studentTotalNum = data.ydrenshu;
        _that.formData.studentAttendNum = data.sdrenshu;
        _that.formData.teacherName = data.truename;
        _that.formData.teacherCode = data.gonghao;
        _that.formData.teacherDepartment = null;
        _that.formData.courseId = data.nid;
        _that.formData.courseName = data.ntitle;
        _that.formData.courseContent = data.ptitle;
        _that.formData.location = null;
        _that.formData.teachSection = data.jieci;
      }).catch((error) => {
        console.error(error);
        // 跳转到选择课程页面
        uni.showToast({
          title: '获取上课信息失败',
          duration: 1000,
          complete: function () {
            // 跳转到下一步
            uni.redirectTo({
              url: `/pages/eval/index`
            })
          }
        });
      });
    },
    // 根据当前时间获取学期学年字段
    getAcademicYearAndSemester(){
      // 获取当前日期
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth() + 1; // 月份从 0 开始，所以要加 1

      let academicYear;
      let semester;
      if (currentMonth >= 9) {
        // 如果当前月份是 9 月及以后，学年从当前年份到下一年份
        academicYear = `${currentYear}-${currentYear + 1}`;
        semester = '第一学期';
      } else if (currentMonth >= 2) {
        // 如果当前月份是 2 月到 8 月，学年从去年到当前年份
        academicYear = `${currentYear - 1}-${currentYear}`;
        semester = '第二学期';
      } else {
        // 如果当前月份是 1 月，学年从去年到当前年份
        academicYear = `${currentYear - 1}-${currentYear}`;
        semester = '第一学期';
      }
      this.formData.schoolYear = academicYear;
      this.formData.semester = semester;
    },
    // 下一步按钮提交
    goProStage() {
      const _that = this;
      //判断是否登录
      if (!isLogin(_that)) {
        return;
      }
      // 表单必填项验证
      _that.$refs.regRef.validate().then(res => {
        // 校验照片是否上传
        if(_that.formData.teachImg == "" || _that.formData.teachImg == null){
          uni.showToast({
            title: '请上传上课现场照片',
            duration: 2000
          });
          return;
        }

        // 请求接口提交基础信息
        addRecord(_that.formData).then(response => {
          // 显示成功提示
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
            complete: function () {
              // 跳转到下一步
              uni.navigateTo({
                url: `/pages/eval/eval_2?recordId=${response.data}`
              })
            }
          });
        }).catch((error) => {
          console.error(error);
        });
      })
    },
	 // 拍照方法
	    takePhoto() {
        const _that = this;
	      uni.chooseImage({
	        count: 1, // 最多选择 1 张图片
	        sourceType: ['camera'], // 只允许使用相机拍照
	        success: (res) => {
            console.log(res)
            // 上传图片
            this.uploadPhoto(res.tempFilePaths[0],_that);
	        },
	        fail: (err) => {
	          console.error('拍照失败:', err);
	        }
	      });
	    },
	    // 上传图片方法
	    uploadPhoto(imageTempPath,_that) {
	      if (!imageTempPath) {
	        return;
	      }
	      uni.uploadFile({
	        url: process.env.VUE_APP_BASE_API+"/common/upload?filePath=teachImg", // 替换为实际的服务器上传接口地址
          header: {
            Authorization: "Bearer " + getToken(),
          },
	        filePath: imageTempPath,
	        name: 'file', // 服务器接收文件的字段名
	        success: (res) => {
	          if (res.statusCode === 200) {
	            uni.showToast({
	              title: '上传成功',
	              icon: 'success'
	            });
              const resObj = JSON.parse(res.data);
              _that.teachImg = process.env.VUE_APP_BASE_API+resObj.fileName;
              _that.formData.teachImg = resObj.fileName;
	          } else {
	            console.error('上传失败:', res.errMsg);
	            uni.showToast({
	              title: '上传失败',
	              icon: 'none'
	            });
	          }
	        },
	        fail: (err) => {
	          console.error('上传失败:', err);
	          uni.showToast({
	            title: '上传失败',
	            icon: 'none'
	          });
	        }
	      });
	    }
	  }
}
</script>

<style lang="scss">
	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
	.uni-forms-item {
		margin-bottom: 10px !important;
	}
	
	.container {
	  padding: 20px;
	  text-align: center;
	}
	
	.image {
	  width: 100%;
	  height: auto;
	  margin-bottom: 20px;
	}
	
	.button {
	  margin-bottom: 10px;
	}

</style>